/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bingoogolapple.qrcode.core;

import ohos.agp.utils.Rect;
import ohos.agp.utils.RectFloat;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.ImageFormat;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.nio.ByteBuffer;

/**
 * 绘制工具类
 */
public class CanvasUtil {

    /**
     * 创建图片
     *
     * @param width  图片宽度
     * @param height 图片高度
     * @return pixelMap 返回图片
     */
    public static PixelMap createPixelMap(int width, int height)
    {
        PixelMap pixelMap =  null;
        PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
        initializationOptions.size = new Size(width,height);
        initializationOptions.pixelFormat = PixelFormat.ARGB_8888;
        initializationOptions.editable = true;
        pixelMap = PixelMap.create(initializationOptions);
        return pixelMap;
    }

    /**
     * 图片转换成pixelMap
     *
     * @param image 原始图片
     * @return 图片类型
     */

    public static   PixelMap image2Pixel(ohos.media.image.Image image)
    {
        if(image == null)
        {
            LogUtil.error("image2Pixel:image == null");
            return null;
        }


        ohos.media.image.Image.Component component =
                image.getComponent(ImageFormat.ComponentType.JPEG);

        LogUtil.info("size:w:"+image.getImageSize().width+",h:"+image.getImageSize().height);
        byte[] bytes = new byte[component.remaining()];
        ByteBuffer buffer = component.getBuffer();
        buffer.get(bytes);
        ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
        ImageSource imageSource = ImageSource.create(bytes,sourceOptions);
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
        return pixelMap;
    }





    /**
     * 变换矩形框方法
     *
     * @param rect 初始矩形框
     * @return ReactFloat 变换矩形框
     */
    public static RectFloat trasnsRectFfromRect(Rect rect)
    {
        RectFloat rectFloat = new RectFloat();
        if(rect==null)
        {
            return rectFloat;
        }
        rectFloat = new RectFloat(rect.left,rect.top,rect.right,rect.bottom);
        return rectFloat;
    }

}
